<?php

namespace app\admin\controller;

use app\common\controller\Backend;

class Admin extends Backend
{
    public $navTitle = "admin";

    public function __construct()
    {
        parent::__construct();

        $this->AdminModel = model('Admin');
    }

    public function index()
    {
        $adminList = model('Admin')->paginate(10);

        if ($this->request->isAjax()) {
            // TODO 接收所有参数
            $formData = $this->request->param();

            if (empty($formData['nickname']) && $formData['state'] == null) $this->error('请输入查询的条件');

            if (empty($formData['nickname']) && $formData['state'] != null) {
                // halt($formData);
                $admin = model('Admin')->where('state', $formData['state'])->select();

                // halt(count($admin));
                $data = ListHtml($admin, 'admin/admin/edit');

                $admin == null ? $this->error('该管理员不存在') : $this->success('查询成功', null, $data);
            }

            if (!empty($formData['nickname']) && $formData['state'] == null) {
                $nickname = $formData['nickname'];
                $admin = model('Admin')->where('nickname', 'like', "%{$nickname}%")->paginate(10);

                $data = ListHtml($admin, 'admin/admin/edit');

                // halt($data);

                $admin == null ? $this->error('该管理员不存在') : $this->success('查询成功', null, $data);
            }

            if (!empty($formData['nickname']) && $formData['state'] != null) {
                $nickname = $formData['nickname'];
                $admin = model('Admin')
                    ->where('nickname', 'like', "%{$nickname}%")
                    ->where('state','like',"{$formData['state']}")
                    ->select();

                $data = ListHtml($admin, 'admin/admin/edit');

                // halt($data);

                $admin == null ? $this->error('该管理员不存在') : $this->success('查询成功', null, $data);
            }
        }

        return $this->fetch('', [
            'navTitle' => $this->navTitle,
            'adminList' => $adminList
        ]);
    }

    public function add()
    {
        if ($this->request->isPost()) {
            $formData = $this->request->param();

            // if (!captcha_check($formData['vercode'])) $this->error('验证码不正确');

            if ($formData['pass'] != $formData['repass']) $this->error('两次密码不一致');

            $salt = build_ranstr();

            $password = md5($formData['pass'] . $salt);

            // TODO 封装数据
            $data = [
                'username' => $formData['username'],
                'nickname' => $formData['nickname'],
                'password' => $password,
                'salt' => $salt,
                'state' => 1
            ];

            // TODO 插入数据
            $result = model('Admin')->validate('common/Admin/Admin')->save($data);

            if ($result === FALSE) {
                $this->error(model('Admin')->getError());
            } else {
                $this->success('用户创建成功', url('admin/admin/index'));
            }
        }

        return $this->fetch('', [
            'navTitle' => $this->navTitle
        ]);
    }

    public function edit()
    {
        $adminid = $this->request->param('id', '');
        $admin = $this->AdminModel->find($adminid);

        if (!$admin) $this->error('管理员不存在');

        if ($this->request->isPost()) {
            // TODO 接收表单数据
            $formData = $this->request->param();

            // if(!captcha_check($formData['vercode'])) $this->error('验证码错误');

            if ($this->LoginAdmin['id'] == $formData['id'] && $formData['state'] == 0) $this->error('不能修改当前登录的管理员账号状态！');

            // TODO 封装数据
            $data = [
                'id' => $adminid,
                'username' => $formData['username'],
                'nickname' => $formData['nickname'],
                'state' => $formData['state']
            ];

            if (!empty($formData['pass'])) {
                if ($formData['pass'] != $formData['repass']) $this->error('两次输入的密码不一致');

                $oldpass = md5($formData['pass'] . $admin['salt']);

                if ($oldpass == $admin['password']) $this->error('新密码与旧密码一致');

                $salt = build_ranstr();

                $password = md5($formData['pass'] . $salt);

                $data['password'] = $password;

                $data['salt'] = $salt;
            } else {
                $data['password'] = $admin['password'];
                $data['salt'] = $admin['salt'];
            }

            $result = $this->AdminModel->validate('common/Admin/Admin')->isUpdate()->save($data);

            if ($result === FALSE) {
                $this->error('更新失败,' . $this->AdminModel->getError());
            } else {
                // if(!empty($formData['pass']) || $formData['state'] == 0) $this->success('当前登录的管理员信息更新成功，请重新登陆', url('admin/index/login'));
                $this->success('管理员信息更新成功', url('admin/admin/index'));
            }
        }

        return $this->fetch('', [
            'navTitle' => $this->navTitle,
            'admin' => $admin
        ]);
    }

    public function delete()
    {
        if ($this->request->isAjax()) {
            $action = $this->request->param('action', '');

            if ($action == 'del') {
                $adminid = $this->request->param('adminid', '');

                if ($adminid == $this->LoginAdmin['id']) $this->error('不能删除当前账号');

                $admin = $this->AdminModel->find($adminid);

                if (!$admin) $this->error('管理员不存在');

                $result = $this->AdminModel->destroy($adminid);

                if ($result === FALSE) $this->error('删除失败');

                $this->success('删除成功', url('admin/index/login'));
            }

            if ($action == 'dels') {
                // TODO 接收所有数据
                $formData = $this->request->param();
                // TODO 转存idArr
                $idArr = $formData['idArr'];

                if (in_array($this->LoginAdmin['id'], $idArr)) $this->error('不能删除当前账号，请重新选择');

                $result = $this->AdminModel->destroy($idArr);

                if ($result === FALSE) $this->error('删除失败');

                $this->success('删除成功', url('admin/index/login'));
            }
        }
    }

    public function editstates()
    {
        if ($this->request->isAjax()) {
            // TODO 接收所有数据
            $formData = $this->request->param();
            // TODO 转存idArr
            $idArr = $formData['idArr'];

            $adminList = $this->AdminModel->select($idArr);

            // halt($adminList);

            // TODO 封装数据
            $dataList = [];

            if ($formData['action'] == 'stop') {
                // TODO 判断当前登录管理员是否在修改数组内
                if (in_array($this->LoginAdmin['id'], $idArr)) $this->error('不能修改当前登录的管理员账号状态！');
                // TODO 判断所选数据中已有禁用的管理员
                foreach ($adminList as $item) {
                    if ($item['state'] == 0) {
                        $this->error('所选数据中存在已禁用的管理员，请重新选择');
                    }
                }

                foreach ($idArr as $item) {
                    $dataList[] = [
                        'id' => $item,
                        'state' => 0
                    ];
                }

                $result = $this->AdminModel->isUpdate()->saveAll($dataList);

                if ($result === FALSE) $this->error('禁用失败,' . $this->AdminModel->getError());

                $this->success('禁用成功');
            }

            if ($formData['action'] == 'start') {
                foreach ($adminList as $item) {
                    if ($item['state'] == 1) {
                        $this->error('所选数据中存在已启用的管理员，请勿重复选择');
                    }
                }

                foreach ($idArr as $item) {
                    $dataList[] = [
                        'id' => $item,
                        'state' => 1
                    ];
                }

                $result = $this->AdminModel->isUpdate()->saveAll($dataList);

                if ($result === FALSE) $this->error('开启失败,' . $this->AdminModel->getError());

                $this->success('开启成功');
            }
        }
    }

    public function appman()
    {
        if ($this->request->isAjax()) {
            $action = $this->request->param('action', '');
            // TODO 接收数据
            $formData = $this->request->param();
            // halt($idArr);

            if ($action == 'return') {
                $adminid = $this->request->param('adminid', '');

                $admin = $this->AdminModel->onlyTrashed()->find($adminid);

                if (!$admin) $this->error('帖子不存在');

                $admin->restore() === FALSE ? $this->error('还原失败') : $this->success('还原成功', url('admin/admin/index'));
            }

            if ($action == 'returns') {
                // TODO 转存idArr
                $idArr = $formData['idArr'] ? $formData['idArr'] : [];

                $result = $this->AdminModel->onlyTrashed()->whereIn('id', $idArr)->update(['deletetime' => null]);

                $result === FALSE ? $this->error(' 还原失败,') : $this->success('还原成功');
            }

            if ($action == 'del') {
                $adminid = $this->request->param('adminid', '');

                $admin = $this->AdminModel->onlyTrashed()->find($adminid);

                if (!$admin) $this->error('帖子不存在');

                $result = $this->AdminModel->destroy($adminid, true);

                $result === FALSE ? $this->error('删除失败') : $this->success('删除成功');
            }

            if ($action == 'dels') {
                // TODO 接收所有数据
                $formData = $this->request->param();
                // TODO 转存idArr
                $idArr = $formData['idArr'];

                $result = $this->AdminModel->destroy($idArr, true);

                $result === FALSE ? $this->error('删除失败') : $this->success('删除成功');
            }
        }

        $adminList = $this->AdminModel->onlyTrashed('deletetime')->order('deletetime', 'desc')->paginate(5);

        return $this->fetch('', [
            'navTitle' => $this->navTitle,
            'adminList' => $adminList
        ]);
    }
}
